package beans;

import dao.DocumentDAO;
import model.Document;
import utils.GetBeanUtil;
import utils.UpdateUtil;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import java.io.File;
import java.util.List;

@ManagedBean(name = "userDocumentsBean")
@ViewScoped
public class UserDocumentsBean {
    private List<Document> documents;

    public UserDocumentsBean() {
        DocumentDAO documentDAO = new DocumentDAO();
        UserBean userBean = (UserBean) GetBeanUtil.getBean("userBean");
        documents = documentDAO.getDocumentsByUserId(userBean.getUser().getIdUser());
    }

    public List<Document> getDocuments() {
        return documents;
    }

    public void setDocuments(List<Document> documents) {
        this.documents = documents;
    }

    public void deleteDocument(int id) {
        try {
            DocumentDAO documentDAO = new DocumentDAO();
            documentDAO.deleteDocumentById(id);
            new File("D:\\FILES\\" + id).delete();
            UpdateUtil.updatePage();
        }
        catch (Exception e) {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage("Error", e.toString()));

        }
    }
}
